<template>
    <div class="container">
        <div class="left">
            <div class="left_top">
                <vue-seamless-scroll :data="notices" :class-option="scrollClassOption">
                    <ul class="item">
                        <li v-for="item in notices" :key="item.id" style="cursor:pointer">
                            <a :href="`/notices/preview/${item.id}`" target="_blank">
                                {{ item.typeName }}</a>
                            <a :href="`/notices/preview/${item.id}`" target="_blank">
                                {{ item.createTime }}</a>
                            <a :href="`/notices/preview/${item.id}`" target="_blank"
                               style="color: #dd6161">{{ item.title }}</a>
                            <a :href="`/notices/preview/${item.id}`" target="_blank"
                               style="color: #dd6161">{{ item.summary }}</a>
                        </li>
                    </ul>
                </vue-seamless-scroll>
            </div>
            <div class="login-bg">
                <img :src="loginLogoBackgroundUrl" alt="登录背景图" style="width:550px;background-size:contain;"/>
            </div>
        </div>
        <div class="right">
            <el-card class="login-wrapper">
                <div style="line-height:90px;font-size:25px;">
                    <!-- <img :src="systemLogoUrl" style="width: 272px;height: 92px" alt="系统LOGO"/> -->
                    基于人工智能的病理诊断系统
                </div>
                <div class="login-form">
                    <div>
                        <el-input placeholder="请输入用户名" v-model="username">
                            <font-awesome-icon :icon="['fas', 'user']"
                                               slot="prepend">
                            </font-awesome-icon>
                        </el-input>
                    </div>
                    <div>
                        <el-input placeholder="请输入密码" type="password"
                                  @submit.native.prevent
                                  @keyup.13.native="userLogin" v-model="password">
                            <font-awesome-icon :icon="['fas', 'lock']"
                                               slot="prepend">
                            </font-awesome-icon>
                        </el-input>
                    </div>
                    <div style="margin-top: 12px;">
                        <el-button type="primary" @click="userLogin">登 录</el-button>
                    </div>
                    <div style="margin-top: 12px;">
                        <el-button type="text" size="mini" @click="downloadDialog = true">
                            推荐浏览器下载
                        </el-button>

                        <el-dialog :close-on-click-modal="false"
                                   :visible.sync="downloadDialog"
                                   title="推荐浏览器下载">
                            <el-tabs type="border-card" stretch="true"
                                     style="width: 100%;" v-model="showSystem">
                                <el-tab-pane style="margin-top: 4px;"
                                             label="Windows版本" name="Windows">
                                    适用于 Windows 10/8.1/8/7 64 位
                                    <!--<a :href="`${browserDownloadURL}${chromeForWindows}`">
                                    <span>下载</span></a>-->
                                </el-tab-pane>
                                <el-tab-pane style="margin-top: 4px;"
                                             label="Mac" name="Mac">
                                    适用于 Mac OS X 10.8 或更高版本
                                    <!--<a :href="`${browserDownloadURL}${chromeForMac}`">
                                    <span>下载</span></a>-->
                                </el-tab-pane>
                                <el-tab-pane style="margin-top: 4px;"
                                             label="Linux" name="Linux">
                                    适用于 Linux fedora 和 openSUSE 系统
                                    <!--<a :href="`${browserDownloadURL}${chromeForLinux}`">
                                    <span>下载</span></a>-->
                                </el-tab-pane>
                            </el-tabs>
                        </el-dialog>
                    </div>
                </div>
            </el-card>
        </div>
        <el-dialog
            :visible.sync="isResetVisible"
            :title="resetMessage"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="40%">
            <el-form label-width="80px" :model="resetForm" :rules="resetRule" ref="resetForm">
                <el-row class="reset-row">
                    <el-col :span="24">
                        <el-form-item label="身份证号" prop="pCardId">
                            <el-input
                                placeholder="身份证号"
                                v-model="resetForm.pCardId"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-button class="login-button longin-reset" @click="loginResetset" :loading="isResetLoading">
                            用户重置并登录
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import moment from 'moment/moment';
import VueSeamlessScroll from 'vue-seamless-scroll';
import { isPromptLoginMessage } from '@/client/libs/util';

export default {
    name: 'Login',
    components: {
        VueSeamlessScroll,
    },
    data() {
        const checkNumber = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('身份证号不能为空'));
            }
            const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
            if (reg.test(value)) {
                return callback();
            }
            return callback(new Error('请输入正确的身份证号'));
        };
        return {
            isResetVisible: false,
            resetForm: { pCardId: '' },
            resetRule: {
                pCardId: [ // 身份证号码
                    {
                        type: 'number',
                        validator: checkNumber,
                        message: `请输入身份证号`,
                        trigger: 'blur'
                    }
                ],
            },
            isResetLoading: false,
            resetMessage: '帐号已经登录!请输入身份证号重置,若重置失败,请联系管理员!',
            notices: [],
            scrollClassOption: {
                // 轮播鼠标控制停止
                hoverStop: true,
                // 轮播速度
                step: 0.4,
                // 开始无缝滚动最小数据长度
                limitMoveNum: 1,
                direction: 1, // 0 往下 1 往上 2向左 3向右
                switchDisabledClass: 'NO',
            },
            // 系统logo
            systemLogoUrl: '/images/logo-new.png',
            // 登录背景图
            loginLogoBackgroundUrl: '/images/login-bg.png',

            username: '',
            password: '',

            downloadDialog: false,
        };
    },

    mounted() {
        this.$store.commit('stateInit');
        this.noticesRequest();
    },

    computed: {
        showSystem() {
            const p = navigator.platform;
            if (p.indexOf('Win') === 0) {
                return 'Windows';
            }
            if (p.indexOf('Mac') === 0) {
                return 'Mac';
            }
            if ((p === 'X11') || (p.indexOf('Linux') === 0)) {
                return 'Linux';
            }

            return 'Windows';
        },
    },

    methods: {
        // 识别关键字以 PROXY- 开头
        async noticesRequest() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/notices/bare',
                })
                    .then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }

                        // 请求成功
                        const result = res.data;
                        console.log('result', result);
                        // 查询结果数据
                        this.notices = [];
                        result.data.forEach((t) => {
                            const item = {
                                id: t.id,
                                typeName: t.typeName,
                                createTime: moment(t.createTime)
                                    .format('YYYY-MM-DD'),
                                title: t.title,
                                summary: t.summary,
                            };
                            this.notices.push(item);
                        });
                    });
            } catch (e) {
                // 跳出
            }
        },
        async userLogin() {
            // 使用 try catch模式
            try {
                let Base64 = require('js-base64').Base64;
                let _this = this;
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/login',
                    params: {
                        username: this.username,
                        password: Base64.encode(this.password),
                    },
                })
                    .then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            const message = res.data.message;
                            if (res.data.code === 500 && !res.data.data) {
                                this.isResetVisible = true;
                                return;
                            }
                            if (isPromptLoginMessage(message, 'LOGIN')) {
                                _this.$message.warning(message);
                            }
                            return;
                        }
                        // 请求成功
                        const result = res.data.data;

                        const platform = {
                            name: '浦东医院病理平台',
                        };
                        const user = {
                            id: result.userInfo.id,
                            name: result.userInfo.name,
                            headImgUrl: result.userInfo.headUrl,

                        };
                        const permissionList = result['ui-item'];
                        console.log('permissionList-before', permissionList);
                        for (let init = 0; init < permissionList.length; init++) {
                            for (let i = 0; i < permissionList[init].permissionList.length; i++) {
                                const iconString = permissionList[init].permissionList[i].icon;
                                const [prefix, icon] = _.split(iconString, ' ');
                                permissionList[init].permissionList[i].prefix = prefix;
                                permissionList[init].permissionList[i].icon = icon;
                            }
                        }
                        console.log('permissionList-after', permissionList);
                        // 存储缓存数据
                        this.$store.commit('setPlatform', platform);
                        this.$store.commit('setUser', user);
                        this.$store.commit('setPermissionList', permissionList);
                        this.$store.commit('loginTimeFlash');
                        // 设置登陆后的跳转页
                        this.$store.commit('setPropertyGeneral', {
                            key: 'nowRoute',
                            value: permissionList[0].permissionList[0].route
                        });

                        this.$router.push({
                            path: permissionList[0].permissionList[0].route,
                        });

                        this.$axios({
                            method: 'GET',
                            url: `/PROXY-Remote/institutions/${result.userInfo.institutionId}`,
                        })
                            .then((res2) => {
                                console.log(res2);
                                if (res2 && res2.data.code === 200) {
                                    const info = res2.data.data;
                                    const institution = {
                                        id: info.id,
                                        isPlatform: info.isPlatform,
                                        name: info.name,
                                        isEnableTaskClaim: info.isEnableTaskClaim,
                                    };
                                    this.$store.commit('setInstitution', institution);
                                }
                            });
                    });
            } catch (e) {
                if (isPromptLoginMessage(e.message, 'LOGIN')) {
                    this.$message.error(e.message);
                }
            }
        },
        async loginResetset() {
            let isValidate = false;
            this.$refs.resetForm.validate((valid) => {
                if (valid) {
                    isValidate = true;
                }
            });
            if (!isValidate) {
                return;
            }
            this.isResetLoading = true;
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/login/reset/token/card/id/${this.username}/${this.resetForm.pCardId}`,
            })
                .then((res) => {
                    this.resetCount += 1;
                    this.isResetVisible = false;
                    // 请求失败
                    if (res.data.code !== 200 || !res.data.data) {
                        const message = '重置登录失败，请联系管理员重置！！！'
                        if (isPromptLoginMessage(message, 'LOGIN')) {
                            this.$message.warning({ message });
                        }
                        return;
                    }
                    this.userLogin();
                });
            this.resetForm.pCardId = '';
            this.isResetLoading = false;
        },
    },
};
</script>

<style scoped>
.left {
    float: left;
    width: 50%;
    height: 400px;
}

.right {
    width: 50%;
    margin-left: 50%;
    height: 400px;
}

.left_top {
    width: 100%;
    margin-top: 10px;
    height: 100px;
    overflow: hidden;
    font-size: small;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.left_top a {
    color: #00BE8B;
    text-decoration: blink;
    background: #FFFFFF;
}

.container {
    width: 1100px;

    margin: 0 auto;
}

.login-bg {
    margin-left: 35px;
    margin-top: 10px;
    float: left;
}

.login-wrapper {
    width: 420px;
    padding: 16px;
    margin-top: 120px;
    background: #FFFFFF;
    /*border-radius: 2px;*/
    /*box-shadow: 2px 1px 3px 1px rgba(26, 26, 26, 0.1);*/
    /*box-sizing: border-box;*/
    text-align: center;
    float: right;
}

.login-form {
    margin-top: 32px;
    margin-bottom: 100px;
}

.login-form div {
    margin: 10px 20px 8px 6px;
    border-bottom: #f4f4f4 1px;
}

.login-form button {
    width: 100%;
    margin: 10px 20px 8px 6px;
}

.login-button {
    background-color: #10A1DF;
    color: white;
    border: #10A1DF 1px;
}

.reset-row /deep/ .longin-reset {
    margin-top: 12px;
    border-radius: 15px;
    min-height: 38px;
    width: 100%;
    height: 38px;
}
</style>
